<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h2>个人设置</h2>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <!-- 个人资料设置 -->
        <el-tab-pane label="个人资料" name="profile">
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="80px"
          >
            <el-form-item label="头像">
              <div class="avatar-uploader">
                <img 
                  :src="userAvatarUrl ? getAvatarUrl(userAvatarUrl) : defaultAvatar" 
                  class="el-avatar el-avatar--circle" 
                  style="height: 100px; width: 100px; object-fit: cover;"
                />
                <el-upload
                  class="upload-btn"
                  action="#"
                  :http-request="customUploadAvatar"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                >
                  <el-button size="small" type="primary">更换头像</el-button>
                </el-upload>
              </div>
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname" maxlength="20" show-word-limit />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" />
            </el-form-item>
            
            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="profileForm.bio"
                type="textarea"
                :rows="4"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="profileLoading">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 修改密码 -->
        <el-tab-pane label="修改密码" name="password">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入当前密码"
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updatePassword" :loading="passwordLoading">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <el-form label-width="0">
            <el-form-item>
              <el-checkbox v-model="notificationSettings.commentNotify">有人评论我的文章时通知我</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-checkbox v-model="notificationSettings.replyNotify">有人回复我的评论时通知我</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-checkbox v-model="notificationSettings.likeNotify">有人点赞我的文章时通知我</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-checkbox v-model="notificationSettings.followNotify">有人关注我时通知我</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-checkbox v-model="notificationSettings.systemNotify">接收系统通知</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateNotificationSettings" :loading="notificationLoading">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import config from '@/config'

export default {
  name: 'UserSettings',
  
  setup() {
    const store = useStore()
    const activeTab = ref('profile')
    const profileFormRef = ref(null)
    const passwordFormRef = ref(null)
    const profileLoading = ref(false)
    const passwordLoading = ref(false)
    const notificationLoading = ref(false)
    const defaultAvatar = require('@/assets/default-avatar.png')
    
    // 使用Vuex中的用户头像
    const userAvatarUrl = computed(() => store.getters['user/userAvatar'])
    
    // 个人资料表单
    const profileForm = reactive({
      nickname: '',
      email: '',
      bio: '',
      avatar: ''
    })
    
    // 密码表单
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 通知设置
    const notificationSettings = reactive({
      commentNotify: true,
      replyNotify: true,
      likeNotify: true,
      followNotify: true,
      systemNotify: true
    })
    
    // 表单验证规则
    const profileRules = {
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度应在2到20个字符之间', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    }
    
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (passwordForm.confirmPassword !== '') {
          passwordFormRef.value.validateField('confirmPassword')
        }
        callback()
      }
    }
    
    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, trigger: 'blur', validator: validatePass },
        { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, trigger: 'blur', validator: validateConfirmPass }
      ]
    }
    
    // 上传相关
    const uploadHeaders = computed(() => {
      const token = localStorage.getItem('token')
      return { Authorization: token }
    })
    
    // 加载用户信息
    const loadUserInfo = async () => {
      try {
        // 先尝试从store获取用户信息
        const userInfo = store.state.user.userInfo;
        if (userInfo && userInfo.id) {
          profileForm.nickname = userInfo.nickname || '';
          profileForm.email = userInfo.email || '';
          profileForm.bio = userInfo.remark || '';  // 后端使用remark字段存储个人简介
          
          // 设置头像，确保有完整的URL
          if (userInfo.avatarUrl) {
            // 检查是否为完整URL
            if (userInfo.avatarUrl.startsWith('http')) {
              profileForm.avatar = userInfo.avatarUrl;
            } else {
              // 如果是相对路径，添加域名前缀
              profileForm.avatar = window.location.origin + userInfo.avatarUrl;
            }
          }
        } else {
          // 如果store中没有完整信息，则从服务器加载
          await store.dispatch('user/getInfo');
          // 重新获取更新后的用户信息
          const updatedInfo = store.state.user.userInfo;
          if (updatedInfo) {
            profileForm.nickname = updatedInfo.nickname || '';
            profileForm.email = updatedInfo.email || '';
            profileForm.bio = updatedInfo.remark || '';  // 后端使用remark字段存储个人简介
            
            // 设置头像，确保有完整的URL
            if (updatedInfo.avatarUrl) {
              // 检查是否为完整URL
              if (updatedInfo.avatarUrl.startsWith('http')) {
                profileForm.avatar = updatedInfo.avatarUrl;
              } else {
                // 如果是相对路径，添加域名前缀
                profileForm.avatar = window.location.origin + updatedInfo.avatarUrl;
              }
            }
          }
        }
      } catch (error) {
        console.error('加载用户信息失败:', error);
        ElMessage.error('获取用户信息失败，请重新登录');
      }
    }
    
    // 上传头像前验证
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        ElMessage.error('头像只能是 JPG 或 PNG 格式!')
        return false
      }
      
      if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
        return false
      }
      
      return true
    }
    
    // 自定义头像上传方法
    const customUploadAvatar = (options) => {
      const { file } = options
      
      // 创建一个新的随机英文文件名，避免中文文件名问题
      const fileExtension = file.name.substring(file.name.lastIndexOf('.'))
      const safeFileName = `avatar_${Date.now()}${fileExtension}`
      const safeFile = new File([file], safeFileName, { type: file.type })
      
      const formData = new FormData()
      formData.append('file', safeFile)
      
      // 获取token
      const token = localStorage.getItem('token')
      
      // 创建URL - 直接使用代理路径
      let url = '/api/upload/avatar'
      
      // 如果有token，通过URL参数传递
      if (token) {
        url = `${url}?token=${encodeURIComponent(token)}`
      }
      
      console.log('头像上传URL:', url)
      
      // 手动创建一个XMLHttpRequest
      const xhr = new XMLHttpRequest()
      xhr.open('POST', url, true)
      xhr.withCredentials = true
      
      // 只设置安全的header
      xhr.setRequestHeader('Accept', 'application/json')
      
      xhr.onload = function() {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText)
            if (response.code === 0) {
              // 上传成功，获取头像URL
              const avatarUrl = response.data
              console.log('后端返回的头像URL:', avatarUrl);
              
              // 更新Vuex中的用户信息，因为后端已经更新了数据库
              store.commit('user/UPDATE_USER', { avatarUrl });
              
              // 强制刷新整个用户信息，确保所有组件更新
              store.dispatch('user/getInfo').then(userInfo => {
                console.log('头像上传成功后刷新用户信息:', userInfo);
                
                // 使用配置方法获取访问URL
                const accessUrl = config.getDirectAvatarUrl(avatarUrl);
                console.log('头像完整URL应为:', accessUrl);
                
                // 更新本地展示
                userAvatarUrl.value = avatarUrl;
                
                ElMessage.success('头像上传成功');
              }).catch(error => {
                console.error('刷新用户信息失败:', error);
                ElMessage.success('头像上传成功，但刷新用户信息失败');
              });
            } else {
              // 服务器返回错误
              ElMessage.error(response.message || '上传失败')
            }
          } catch (e) {
            console.error('解析响应失败:', e, xhr.responseText)
            ElMessage.error('解析响应失败')
          }
        } else {
          ElMessage.error('上传失败: ' + xhr.status)
        }
      }
      
      xhr.onerror = function() {
        ElMessage.error('网络错误，上传失败')
      }
      
      // 发送表单数据
      xhr.send(formData)
    }
    
    // 更新个人资料
    const updateProfile = () => {
      profileFormRef.value.validate(async (valid) => {
        if (valid) {
          profileLoading.value = true
          try {
            await store.dispatch('user/updateProfile', {
              nickname: profileForm.nickname,
              email: profileForm.email,
              remark: profileForm.bio  // 后端使用remark字段存储个人简介
            })
            
            // 更新成功后重新获取用户信息，确保数据同步
            await store.dispatch('user/getInfo')
            
            ElMessage.success('个人资料更新成功')
          } catch (error) {
            console.error('更新个人资料失败:', error)
            ElMessage.error('更新失败，请稍后重试')
          } finally {
            profileLoading.value = false
          }
        }
      })
    }
    
    // 更新密码
    const updatePassword = () => {
      passwordFormRef.value.validate(async (valid) => {
        if (valid) {
          passwordLoading.value = true
          try {
            await store.dispatch('user/changePassword', passwordForm)
            ElMessage.success('密码修改成功')
            passwordForm.oldPassword = ''
            passwordForm.newPassword = ''
            passwordForm.confirmPassword = ''
          } catch (error) {
            console.error('修改密码失败:', error)
            ElMessage.error('修改失败，请确认当前密码正确')
          } finally {
            passwordLoading.value = false
          }
        }
      })
    }
    
    // 更新通知设置
    const updateNotificationSettings = async () => {
      notificationLoading.value = true
      try {
        // 暂未实现
        ElMessage.success('通知设置已保存')
      } catch (error) {
        console.error('保存通知设置失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      } finally {
        notificationLoading.value = false
      }
    }
    
    // 获取用户头像URL
    const getAvatarUrl = (url) => {
      return config.getDirectAvatarUrl(url);
    }
    
    onMounted(() => {
      // 进入页面时立即加载用户信息
      loadUserInfo()
      
      // 如果存在token，强制重新获取用户信息
      const token = localStorage.getItem('token')
      
      if (token) {
        // 强制重新获取用户信息，确保头像正确显示
        store.dispatch('user/getInfo').then(() => {
          console.log('强制更新用户信息成功');
          // 重新加载表单数据
          loadUserInfo()
        }).catch(error => {
          console.error('获取用户信息失败:', error)
          ElMessage.error('获取用户信息失败，请重新登录')
        })
      }
    })
    
    return {
      activeTab,
      profileForm,
      passwordForm,
      notificationSettings,
      profileFormRef,
      passwordFormRef,
      profileLoading,
      passwordLoading,
      notificationLoading,
      profileRules,
      passwordRules,
      defaultAvatar,
      uploadHeaders,
      beforeAvatarUpload,
      customUploadAvatar,
      updateProfile,
      updatePassword,
      updateNotificationSettings,
      userAvatarUrl,
      getAvatarUrl
    }
  }
}
</script>

<style scoped>
.settings-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.upload-btn {
  margin-top: 10px;
}

@media screen and (max-width: 768px) {
  .settings-container {
    padding: 10px;
  }
}
</style> 